import pygame

class PlaneSprite(pygame.sprite.Sprite):
    """我方飞机类"""
    def __init__(self, speed=1):
        super().__init__()
        self.image = pygame.image.load('./image/me1.png')
        self.rect = self.image.get_rect()
        self.rect.centerx = 240
        self.rect.y = 550
        self.speed = speed

    # def update(self):
    #     self.rect.y+=self.speed

class BgSprite(pygame.sprite.Sprite):
    """背景图片类"""
    def __init__(self, is_pre=False, speed=1):
        super().__init__()
        self.image = pygame.image.load('./image/background.png')
        self.rect = self.image.get_rect()
        if is_pre:
            self.rect.y = -700
        self.speed = speed

    def update(self):
        self.rect.y += self.speed
        if self.rect.y >= 700:
            self.rect.y = -700


class PlaneGame():
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((480, 700))
        pygame.display.set_caption('飞机大战')
        self.is_loop = True
        self.clock = pygame.time.Clock()
        self.create_sprite()

    def start(self):
        while self.is_loop:
            self.event_handler()
            self.screen.fill((0, 0, 0))
            self.update_sprite()
            # pygame.draw.circle(self.screen, (255, 0,0), (240, 600),20)
            self.clock.tick(40)
            pygame.display.update()
        pygame.quit()

    def create_sprite(self):
        bg = BgSprite(speed=5)
        bg1 = BgSprite(True, speed=5)
        self.bg_group = pygame.sprite.Group(bg, bg1)
        self.hero = PlaneSprite()
        self.plane_group = pygame.sprite.Group(self.hero)

    def update_sprite(self):
        self.bg_group.update()
        self.bg_group.draw(self.screen)
        self.plane_group.draw(self.screen)

    def event_handler(self):
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.is_loop = False
            if e.type==pygame.KEYDOWN:
                if e.key == pygame.K_LEFT:
                    self.hero.rect.x-=10
                    if self.hero.rect.x < 0:
                        self.hero.rect.x=10
                elif e.key == pygame.K_RIGHT:
                    self.hero.rect.x+=10
                    if self.hero.rect.right > 480:
                        self.hero.rect.right = 470


pg = PlaneGame()
pg.start()

